/*
* Copyright 2010 Pavel Kozhin 
*
* Licensed under the Apache License, Version 2.0 (the "License"); 
* you may not use this file except in compliance with the License. 
* You may obtain a copy of the License at 
* 
* http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software 
* distributed  under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
* See the License for the specific language governing permissions and 
* limitations under the License.
*
* Author: Pavel Kozhin.
*/

package org.bookmarksframework.rule
{
	public class RuleParser implements IRuleParser
	{
		public function validate(value:*):Boolean
		{
			var str:String = rule as String;
			return (str) ? (str.search(value) >= 0) : false;
		}
		
		// TODO: Optimize
		public function findValue(value:*):*
		{
			var result:* = helper(value, value, 0);
			var resultNum:Number = parseFloat(result);
			
			return !isNaN(resultNum) ? resultNum : result;
		}
		
		public function findPath(value:*):*
		{
			return helper(value, value + "=", 1);
		}
		
		private var _rule:Object;
		
		public function get rule():Object
		{
			return _rule;
		}
		
		public function set rule(value:Object):void
		{
			_rule = value;
		}
		
		private function helper(value:*, search:String, pairsIndex:int):*
		{
			var result:* = null;
			var str:String = value as String;
			var ruleValue:String = rule as String;
			var pair:String;
			var pairs:Array;
			var pairsArr:Array;
			var pairsLen:int;
			var resultNum:Number;
			
			pairs = ruleValue.split(";");
			pairsLen = pairs.length;
			
			for (var i:int = 0; i < pairsLen; ++i)
			{
				pair = pairs[i] as String;
				
				if (pair.indexOf(search) != -1)
				{
					pairsArr = pair.split("=");
					result = (pairsArr.length < 2) ? null : pairsArr[pairsIndex];
					break;
				}
			}
			
			return result;
		}
	}
}